package com.toprs.base.utils

import cn.afterturn.easypoi.excel.ExcelExportUtil
import cn.afterturn.easypoi.excel.entity.TemplateExportParams
import com.toprs.base.entity.Log
import com.toprs.base.exception.CustomException
import org.apache.commons.codec.binary.Base64
import org.springframework.core.io.ClassPathResource
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.nio.charset.Charset
import java.text.SimpleDateFormat


class FileUtil {
    companion object {

        fun saveGeojson(path: String, content: String) {
            val f = File(path)
            if (content.startsWith("http")) {
                val oldName = content.split("/").reversed()[0].split("?time")[0]
                File(f.parent + File.separator + oldName).renameTo(f)
            } else {
                f.writeText(content, Charset.forName("UTF-8"))
            }
        }

        fun deleteGeojsons(path: String, id: Int) {
            val list = File(path).listFiles()?.filter { it.name.startsWith("program-$id-") }
            list?.forEach {
                it.delete()
            }
        }

        fun deleteFile(s: String) {
            val f = File(s)
            if (f.isFile && f.exists()) {
                f.delete()
            }
        }

        @Throws(IOException::class)
        fun exportExcelLog(list: List<Log>, title: String, dataPath: String): String {

            val path = "${dataPath}/excel/${System.currentTimeMillis()}.xls"
            if (!File(path).parentFile.exists()) File(path).parentFile.mkdir()

            val inputStream = ClassPathResource("logManager.xlsx").inputStream

            val params = TemplateExportParams(inputStream)
            val map: MutableMap<String, Any> = HashMap()
            val format = SimpleDateFormat("YYYY-MM-dd HH:mm:ss")
            val listOut = mutableListOf<MutableMap<String, Any>>()
            for (i in list.indices) {
                val data = list[i]
                val obj = mutableMapOf<String, Any>()
                obj["id"] = i + 1
                obj["logTypeName"] = data.logTypeName.orEmpty()
                obj["username"] = data.username.orEmpty()
                obj["logContent"] = data.logContent.orEmpty()
                obj["ip"] = data.ip.orEmpty()
                obj["createTime"] = format.format(data.createTime)
                listOut.add(obj)
            }

            map["maplist"] = listOut
            map["title"] = title
            val workbook = ExcelExportUtil.exportExcel(params, map)
            val fos = FileOutputStream(path)
            workbook.write(fos)
            fos.close()
            return path
        }

        @Throws(IOException::class)
        fun file2base64(filePath: String): String {

            var file = File(filePath)
            if (!file.exists()) {
                if (file.name.endsWith(".pdf")) {
                    val filePath2 = file.name.replace(".pdf", ".PDF")
                    file = File(file.parent + File.separator + filePath2)
                } else {
                    throw CustomException("文件不存在！")
                }
            }
            if (!file.exists()) {
                throw CustomException("文件不存在！")
            }

            val inputStream = FileInputStream(file)
            val bytes = ByteArray(file.length().toInt())
            inputStream.read(bytes)
            inputStream.close()
            return Base64.encodeBase64String(bytes)
//            String(Base64.encodeBase64(bytes), Charsets.UTF_8)

        }


    }
}